package com.toutou.base.activity

import android.content.pm.ActivityInfo
import android.graphics.Rect
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.toutou.base.util.ActivitiesManager
import com.toutou.base.util.hideSoftKeyboard
import com.toutou.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.getVmClazz
import me.hgj.jetpackmvvm.ext.inflateBindingWithGeneric

/**
 * 描述　: 包含ViewModel 和Databind ViewModelActivity基类，把ViewModel 和Databind注入进来了
 * 需要使用Databind的清继承它
 */
abstract class BaseActivity<VM : BaseViewModel, DB : ViewDataBinding> : AppCompatActivity() {

    lateinit var mViewModel: VM

    lateinit var mDatabind: DB

    abstract fun initView(savedInstanceState: Bundle?)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initOrientation()
        setContentView(initDataBind())

        ActivitiesManager.addActivity(this)//在init的前面，保障在init中可以使用ActivitiesManager
        mViewModel = ViewModelProvider(this)[getVmClazz(this)]
        initView(savedInstanceState)
    }

    open fun initOrientation() {
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT //默认强制竖屏
    }
    /**
     * 创建DataBinding
     */
    private fun initDataBind(): View {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        mDatabind = inflateBindingWithGeneric(layoutInflater)
        return mDatabind.root
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (v is EditText) {
                val outRect = Rect()
                v.getGlobalVisibleRect(outRect)
                val otherOutRect = Rect()
                otherNotMissKeyBoardView()?.getGlobalVisibleRect(otherOutRect)
                if (!outRect.contains(ev.rawX.toInt(),ev.rawY.toInt()) && !otherOutRect.contains(ev.rawX.toInt(),ev.rawY.toInt())) {
                    hideSoftKeyboard(this, v)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    open fun otherNotMissKeyBoardView(): View? {
        return null
    }
}